package com.yinile.zc04.service;


import java.util.UUID;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import com.yinile.zc04.sys.page.Pagination;
import com.yinile.zc04.sys.result.BaseResult;
import com.yinile.zc04.sys.result.ObjectOkResult;
import com.yinile.zc04.sys.utils.StringUtils;
import com.yinile.zc04.dao.AuthorRepository;
import com.yinile.zc04.domain.Author;
import com.yinile.zc04.sys.dao.BaseRepository;
import com.yinile.zc04.sys.exception.NoRecordException;

@Service
public class AuthorService{
	@Autowired
	AuthorRepository authorRepository;
	
	// 必须是org.springframework.transaction.annotation.Transactional
	// 不能是javax包里的 
	@Transactional(readOnly=false)
	public ObjectOkResult save(Author author) {
		author.id = UUID.randomUUID().toString();
		this.authorRepository.save(author);
		return new ObjectOkResult(author);
	}

	public ObjectOkResult findById(String id) {
		if (StringUtils.isEmpty(id)) {
			throw new NoRecordException("缺少ID");
		}
		Author author = this.authorRepository.findById(id);
		if (author == null) {
			throw new NoRecordException("没有这条记录");
		}
		return new ObjectOkResult(author);
	}
	
	
	// 必须是org.springframework.transaction.annotation.Transactional
	// 不能是javax包里的
	@Transactional
	public ObjectOkResult update(Author author) {
		if (StringUtils.isEmpty(author.id)) {
			throw new NoRecordException("缺少ID");
		}
		// 从数据库中查找出来的实体
		Author dbAuthor = this.authorRepository.findById(author.id);
		if (dbAuthor == null) {
			throw new NoRecordException("没有这条记录");
		}
		this.authorRepository.update(author);
		return new ObjectOkResult(author);
	}
	
	// 必须是org.springframework.transaction.annotation.Transactional
	// 不能是javax包里的
	@Transactional
	public BaseResult delete(String id) {
		this.authorRepository.delete(id);
		BaseResult br = new BaseResult();
		br.message = "success";
		return br;
	}

	public ObjectOkResult findByPage(Integer offset, Integer step, String name, String address) {
		if (offset == null) {
			offset = 0;
		}
		if (step == null) {
			step = 2;
		}
		name = StringUtils.trim(name);
		address = StringUtils.trim(address);
		return new ObjectOkResult(this.authorRepository.findByPage(offset, step, name, address));
	}
}
